<template>
  <div class="select-user">
    <div class="content">
      <div class="bars">
        <span class="bar" @click="selectOrgs = []">{{companyName}}</span>
        <span
          class="bar"
          v-for="(org, index) in selectOrgs"
          :key="org.orgId"
          @click="removeBar(index)"
        >{{ org.orgDesc }}</span>
      </div>
      <org-select
        :value="queryListFilter"
        :level="level"
        :selectOrgs="orgIds"
        :selectUsers="users"
        @selectOrg="selectOrg"
        @selectUser="selectUser"
      ></org-select>
    </div>
  </div>
</template>

<script>
import orgSelect from './org.vue';
export default {
  name: 'select-user',
  components: {
    orgSelect,
  },
  props: {
    companyName: [String],
    multiple: {
      type: Boolean,
      default: false,
    },
    selected: {
      type: Array,
      default: () => {
        return [];
      },
    },
    search: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      queryList: [],
      selectOrgs: [],
      selectUsers: [],
    };
  },
  watch: {
    selected: {
      deep: true,
      immediate: true,
      handler(val) {
        this.selectUsers = val || [];
      },
    },
    search:{
      handler(val) {
        this.selectOrgs = []
      }
    }
  },
  computed: {
    queryListFilter() {
      const queryList = this.getTreeInfo(
        this.search
          ? this.setVisible(this.queryList, this.search).filter((i) => i.visible)
          : JSON.parse(JSON.stringify(this.queryList)),
        [0, null],
        0
      );
      return queryList;
    },
    users() {
      return this.selectUsers.map((i) => i.username);
    },
    orgIds() {
      return this.selectOrgs.map((i) => i.orgId);
    },
    level() {
      return this.selectOrgs.length;
    },
  },
  mounted() {
    this.getUserInfo();
  },
  methods: {
    findParent(array, searchVal, parentId) {
      const item = array.find((i) => i.orgId === parentId);
      if (item) {
        item.users = item.users.filter((item) => {
          return (
            item.username?.includes(searchVal) ||
            item.realname?.includes(searchVal)
          );
        });
        item.visible = true;
        this.findParent(array, searchVal, item.parentId);
      }
    },
    setVisible(array, searchVal) {
      const newArray = JSON.parse(JSON.stringify(array));
      for (let i = newArray.length - 1; i >= 0; i--) {
        const item = newArray[i];
        if (!item.visible) {
          item.users = item.users.filter((item) => {
            return (
              item.username?.includes(searchVal) ||
              item.realname?.includes(searchVal)
            );
          });
          item.visible = item.users.length; // || item.orgDesc?.includes(searchVal)
        }
        if (item.visible) {
          this.findParent(newArray, searchVal, item.parentId);
        }
      }
      return newArray;
    },
    removeBar(index) {
      this.selectOrgs.splice(index + 1);
    },
    selectOrg(item) {
      this.selectOrgs.push(item);
    },
    selectUser(item) {
      if (this.multiple) {
        const index = this.selectUsers.findIndex(
          (i) => i.username === item.username
        );
        if (index > -1) {
          this.selectUsers.splice(index, 1);
        } else {
          this.selectUsers.push(item);
        }
      } else {
        this.selectUsers = [item];
      }
      this.$emit('selectUsers', this.selectUsers);
    },
    getUserInfo() {
      this.$http
        .post(
          '/cafe.portal-service/frame_center/define/query/list/org_user_query'
        )
        .then(({ data }) => {
          if (data.success) {
            this.queryList = (data.object.resultList || []).map((item) => {
              item.users = (item.users.split(',') || [])
                .filter((i) => {
                  return i !== '_';
                })
                .map((i) => {
                  const [username, realname] = i.split('_');
                  const avatar = realname && realname.substr(-1);
                  return {
                    username,
                    realname,
                    avatar
                  };
                });
              return item;
            });
          }
        });
    },
    getTreeInfo(queryList, parentIds, level) {
      const list =
        queryList.filter((i) => parentIds.includes(i.parentId)) || [];
      const orgIds = list.map((i) => i.orgId) || [];
      list.forEach((item) => {
        item.orgDesc = this.$locale(item.orgDesc);
        item.level = level;
        item.children =
          this.getTreeInfo(
            queryList.filter((i) => !orgIds.includes(i.orgId)),
            [item.orgId],
            level + 1
          ) || [];
      });
      return list;
    },
  },
};
</script>

<style lang="less" scoped>
.select-user {
  min-width: 200px;
  min-height: 100px;
  background-color: #fff;
  // padding: 4px 8px;
  box-sizing: border-box;
  .content {
    .bars {
      padding: 0 10px;
      font-size: 12px;
      margin: 4px 0px;
      color: #808080;
      cursor: pointer;
      & > span:nth-last-child(1) {
        color: #010101;
      }
      .bar {
        margin: 0px 4px;
        &::after {
          content: '>';
          display: inline-block;
          padding-left: 10px;
        }
        &:nth-last-child(1) {
          &::after {
            display: none;
          }
        }
      }
    }
  }
}
</style>
